package com.arvinclub.web.controller.user;

import com.arvinclub.model.entity.User;
import com.arvinclub.service.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

/**
 * 登录
 */
@Controller
public class LoginController {
    @Resource
    private UserService userService;

    /**
     * 进入登录页面
     */
    @GetMapping({"/", "login.html"})
    public String login(Model model) {
        model.addAttribute(new User());
        return "login";
    }

    /**
     * 登录功能
     */
    @PostMapping({"/", "login.html"})
    public String login(@Valid User user, Errors errors, HttpSession session, RedirectAttributes model) {
        /*检查用户名和密码是否为空*/
        if (errors.hasErrors())
            return "login";
        /*检查用户名和密码是否正确*/
        User realUser = userService.checkUser(user);
        if (realUser != null) {
            session.setAttribute("user", realUser);
            /*清除搜索的记录*/
            session.removeAttribute("blogList");
            session.removeAttribute("keyword");
            session.removeAttribute("page");
            return "redirect:user/blogs.html";
        }
        /*通知是否有错误*/
        model.addFlashAttribute("msg", "err");
        return "redirect:/";
    }

}
